package net.zjitc.controller;

import net.zjitc.domain.MessageConstant;
import net.zjitc.domain.Result;
import net.zjitc.domain.User;
import net.zjitc.domain.PageResult;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping
    public String read(){
        return "hello spring";
    }
    @PostMapping
    public Result add(@RequestBody User user){
        Result result=null;
        try {
            userService.add(user);
        }catch (Exception e){
            return new Result(false, MessageConstant.ADD_USER_FAIL,null);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS,null);
    }
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id")Integer id){
        try {
            userService.deleteById(id);
        }catch (Exception e){
            return new Result(false, MessageConstant.DELETE_USER_FAIL,null);
        }
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS,null);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id){
        User user;
        try {
            user=userService.findById(id);
        }catch (Exception e){
            return new Result(false, MessageConstant.FIND_USER_FAIL,null);
        }
        return new Result(true, MessageConstant.FIND_USER_SUCCESS,user);
    }
    @PutMapping
    public Result update(@RequestBody User user){
        try {
            userService.update(user);
        }catch (Exception e){
            return new Result(false, MessageConstant.UPDATE_USER_FAIL,null);
        }
        return new Result(true, MessageConstant.UPDATE_USER_SUCCESS,null);
    }
    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage,
                              @PathVariable("pageSize") int pageSize,
                              @RequestBody User user){
        PageResult<User> pageResult=null;
        try {
            pageResult=userService.findPage(currentPage,pageSize,user);
        }catch (Exception e){
            return new Result(false,MessageConstant.FIND_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.FIND_USER_SUCCESS,pageResult);
    }
}
